package com.project.common.filter;

import com.project.common.entity.SysUsers;
import com.project.common.service.SysAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckAuthFilter implements HandlerInterceptor {
    @Autowired
    private SysAuthorizationService sysAuthorizationService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String homeUrl=request.getContextPath();
        if (requestURI.endsWith(".png")||requestURI.equals("/favicon.ico")||requestURI.equals("/css/bootstrap.css.map")||requestURI.endsWith(".action")||requestURI.endsWith(".jpg")||requestURI.endsWith(".css")||requestURI.endsWith(".js") || requestURI.endsWith(".html")||requestURI.equals("/SysUsers/loginOut")||requestURI.equals("/SysUsers/loginUser")||requestURI.equals("/login.html")) {
//            System.out.println("放行");
            return true;
        } else {
            HttpSession session = request.getSession();
            SysUsers user = (SysUsers) session.getAttribute("user");
            Boolean b = sysAuthorizationService.checkAuthenticate(user.getId(), requestURI);
            if (b==true)  {
                return true;
            } else {
                if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){
                    response.setHeader("SESSIONSTATUS", "TIMEOUT");
                    response.setHeader("CONTEXTPATH", homeUrl+"/tip.html");
                    // FORBIDDEN，forbidden。也就是禁止、403
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                }else{
                    // 如果不是 ajax 请求，则直接跳转即可
                    response.sendRedirect(homeUrl+"/tip.html");
                }
                return  false;
            }
        }
    }
}
